<template>
  <el-drawer v-model="drawer" :close-on-click-modal="false" :direction="direction">
    <template #header>
      <h4>添加评论</h4>
    </template>
    <template #default>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
        <el-form-item label="酒店名称">
          <el-input v-model="ruleForm.hotelName" disabled />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input 
            v-model="ruleForm.content" 
            placeholder="请输入评论内容"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="ruleForm.rating" :max="5" show-score />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createReview } from '@/api/review'
import { useUserInfoStore } from '@/stores/userInfo'

const emit = defineEmits(['refresh'])
const userInfoStore = useUserInfoStore()

interface RuleForm {
  userId: string
  hotelName: string
  content: string
  rating: number
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userId: '',
  hotelName: '',
  content: '',
  rating: 5
})

const drawer = ref(false)
const direction = ref<'rtl' | 'ltr' | 'ttb' | 'btt'>('rtl')

const rules = reactive<FormRules<RuleForm>>({
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }],
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }]
})

const submitForm = () => {
  if (!userInfoStore.userInfo?.user?.userId) {
    ElMessage.error('用户未登录，无法提交评论')
    return
  }

  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 确保数值字段是正确的格式
      const formData = {
        ...ruleForm,
        // 确保rating是数字类型
        rating: Number(ruleForm.rating),
        // 确保userId是当前登录用户
        userId: userInfoStore.userInfo.user.userId
      };
      
      console.log('提交新增评论数据:', formData);
      
      createReview(formData).then(res => {
        console.log('新增评论响应:', res);
        
        const result = res.data as any;
        
        // 检查返回的数据结构
        if (result === true || result === 'success' || result === 1) {
          // 直接返回成功标志
          ElMessage.success('添加成功');
          handleClose();
          emit('refresh');
        } else if (result && (result.code === 200 || result.code === 0)) {
          // 标准响应格式
          ElMessage.success('添加成功');
          handleClose();
          emit('refresh');
        } else {
          console.error('添加评论失败:', result);
          ElMessage.error(result?.msg || '添加失败');
        }
      }).catch(error => {
        console.error('添加评论错误:', error);
        ElMessage.error('网络错误，添加评论失败');
      });
    }
  })
}

const handleClose = () => {
  drawer.value = false
}

// 修改open方法接收订单信息
const open = (orderData?: any) => {
  drawer.value = true;
  
  // 重置表单
  ruleForm.content = '';
  ruleForm.rating = 5;
  
  // 如果传入了订单数据，自动填充用户ID和酒店名称
  if (orderData && orderData.hotelName) {
    ruleForm.hotelName = orderData.hotelName;
    
    // 从store获取当前用户ID
    if (userInfoStore.userInfo?.user?.userId) {
      ruleForm.userId = userInfoStore.userInfo.user.userId;
    }
  }
}

defineExpose({ open })
</script>
